using SG3L_RAG.Application.Interfaces;
using SG3L_RAG.Domain.Entities;
using SG3L_RAG.Domain.Repositories;
using SG3L_RAG.Application.DTOs;

namespace SG3L_RAG.Application.Services
{
    public class UserService : IUserService
    {
        private readonly IRepository<User> _userRepository;
        private readonly IRepository<Conversation> _conversationRepository;

        public UserService(IRepository<User> userRepository, IRepository<Conversation> conversationRepository)
        {
            _userRepository = userRepository;
            _conversationRepository = conversationRepository;
        }

        // 基本 CRUD 操作
        public async Task<User?> GetByIdAsync(Guid id)
        {
            return await _userRepository.GetByIdAsync(id);
        }

        public async Task<User?> GetByUsernameAsync(string username)
        {
            var users = await _userRepository.GetAllAsync();
            return users.FirstOrDefault(u => u.Username == username);
        }

        public async Task<User?> GetByEmailAsync(string email)
        {
            var users = await _userRepository.GetAllAsync();
            return users.FirstOrDefault(u => u.Email == email);
        }

        public async Task<IEnumerable<User>> GetAllAsync()
        {
            return await _userRepository.GetAllAsync();
        }

        public async Task<User> CreateAsync(string username, string password, string email, string phoneNumber, string role)
        {
            var user = User.Create(username, password, email, phoneNumber, role);
            await _userRepository.AddAsync(user);
            return user;
        }

        public async Task<User> CreateAsync(string username, string password, string email, string role)
        {
            var user = User.Create(username, password, email, role);
            await _userRepository.AddAsync(user);
            return user;
        }

        public async Task UpdateAsync(User user)
        {
            await _userRepository.UpdateAsync(user);
        }

        public async Task<User> UpdateUserAsync(Guid userId, UpdateUserDto updateUserDto)
        {
            var user = await _userRepository.GetByIdAsync(userId);
            if (user == null)
            {
                throw new ArgumentException($"用户不存在，ID: {userId}");
            }

            // 更新用户信息
            user.UpdateUsername(updateUserDto.Username);
            user.UpdateEmail(updateUserDto.Email);
            user.UpdatePhoneNumber(updateUserDto.PhoneNumber);
            user.UpdateRole(updateUserDto.Role);

            await _userRepository.UpdateAsync(user);
            return user;
        }

        public async Task DeleteAsync(Guid id)
        {
            await _userRepository.DeleteAsync(id);
        }

        // 角色和权限操作
        public async Task<IEnumerable<User>> GetUsersByRoleAsync(string role)
        {
            var users = await _userRepository.GetAllAsync();
            return users.Where(u => u.Role == role);
        }

        public async Task<bool> IsAdminAsync(Guid userId)
        {
            var user = await _userRepository.GetByIdAsync(userId);
            return user?.IsAdmin() ?? false;
        }

        public async Task<bool> IsNormalUserAsync(Guid userId)
        {
            var user = await _userRepository.GetByIdAsync(userId);
            return user?.IsNormalUser() ?? false;
        }

        public async Task<bool> HasPermissionAsync(Guid userId, Guid documentId, string permissionType)
        {
            var user = await _userRepository.GetByIdAsync(userId);
            if (user == null) return false;

            // 需要先获取文档实体
            // 这里假设有DocumentRepository，实际项目中需要注入
            // 暂时用简化版本检查权限
            foreach (var permission in user.Permissions)
            {
                if (permission.DocumentId == documentId && permission.PermissionType == permissionType)
                    return true;
            }
            return false;
        }

        public async Task AddPermissionAsync(Guid userId, Permission permission)
        {
            var user = await _userRepository.GetByIdAsync(userId);
            if (user != null)
            {
                user.AddPermission(permission);
                await _userRepository.UpdateAsync(user);
            }
        }

        // 密码和验证操作
        public async Task<bool> ValidateCredentialsAsync(string username, string password)
        {
            var user = await GetByUsernameAsync(username);
            return user?.CheckPassword(password) ?? false;
        }

        public async Task<bool> CheckPasswordAsync(Guid userId, string inputPassword)
        {
            var user = await _userRepository.GetByIdAsync(userId);
            return user?.CheckPassword(inputPassword) ?? false;
        }

        public async Task ChangePasswordAsync(Guid userId, string newPassword)
        {
            var user = await _userRepository.GetByIdAsync(userId);
            if (user != null)
            {
                user.ChangePassword(newPassword);
                await _userRepository.UpdateAsync(user);
            }
        }

        // 用户信息更新操作
        public async Task UpdatePhoneNumberAsync(Guid userId, string phoneNumber)
        {
            var user = await _userRepository.GetByIdAsync(userId);
            if (user != null)
            {
                user.UpdatePhoneNumber(phoneNumber);
                await _userRepository.UpdateAsync(user);
            }
        }

        public async Task UpdateEmailAsync(Guid userId, string email)
        {
            var user = await _userRepository.GetByIdAsync(userId);
            if (user != null)
            {
                user.UpdateEmail(email);
                await _userRepository.UpdateAsync(user);
            }
        }

        // 关联实体操作
        public async Task AddDocumentAsync(Guid userId, Document document)
        {
            var user = await _userRepository.GetByIdAsync(userId);
            if (user != null)
            {
                user.AddDocument(document);
                await _userRepository.UpdateAsync(user);
            }
        }

        public async Task AddConversationAsync(Guid userId, Conversation conversation)
        {
            var user = await _userRepository.GetByIdAsync(userId);
            if (user != null)
            {
                user.AddConversation(conversation);
                await _userRepository.UpdateAsync(user);
            }
        }

        public async Task<IEnumerable<Document>> GetUserDocumentsAsync(Guid userId)
        {
            var user = await _userRepository.GetByIdAsync(userId);
            return user?.Documents ?? new List<Document>();
        }

        public async Task<IEnumerable<Conversation>> GetUserConversationsAsync(Guid userId)
        {
            // 直接使用ConversationService获取用户对话，避免导航属性延迟加载问题
            var conversations = await _conversationRepository.GetAllAsync();
            return conversations.Where(c => c.UserId == userId);
        }

        public async Task<IEnumerable<Permission>> GetUserPermissionsAsync(Guid userId)
        {
            var user = await _userRepository.GetByIdAsync(userId);
            return user?.Permissions ?? new List<Permission>();
        }

        public async Task UpdateAvatarAsync(Guid userId, string? avatar)
        {
            var user = await _userRepository.GetByIdAsync(userId);
            if (user == null)
                throw new ArgumentException("用户不存在");

            user.UpdateAvatar(avatar);
            await _userRepository.UpdateAsync(user);
        }
    }
}
